package tech.yixiyun.framework.kuafu.db.sql.handler;

import tech.yixiyun.framework.kuafu.controller.request.param.ParamType;
import tech.yixiyun.framework.kuafu.db.sql.SqlException;
import org.apache.commons.dbutils.ResultSetHandler;

import java.lang.reflect.Type;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;

/**
 * 单列的处理器
 */
public class ColumnHandler<T> implements ResultSetHandler<T> {


    private Type type;

    /**
     * 接受两种参数，一种是Class类，一种是jackson提供的javatype，用于json反序列化
     * @param columnType
     */
    public ColumnHandler(Type columnType) {
        this.type = columnType;
    }

    @Override
    public T handle(ResultSet rs) throws SQLException {
        if (!rs.next()) {
            if (type instanceof Class) {
                return (T) ParamType.getDefaultValue((Class)type);
            } else {
                return null;
            }

        }
        try {

            ResultSetMetaData metaData = rs.getMetaData();
            String columnLabel = metaData.getColumnLabel(1);
            return (T) ColumnProcessor.process(rs, columnLabel, type);


        } catch (Exception e) {
            if (e instanceof RuntimeException) {
                throw (RuntimeException)e;
            }
            throw new SqlException("构建column数据实例发生异常", e);
        }
    }
}
